package com.wenan.ui.popup
{
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import mx.core.FlexGlobals;
	import mx.core.IFlexDisplayObject;
	import mx.managers.PopUpManager;

	public class DialogUtil
	{
		static private var applicationListenered:Boolean = false;
		private static var dialogTarget:IFlexDisplayObject;
		public function DialogUtil()
		{
		}
		
		public static function show(parent:DisplayObject, dialogClass:Class, 
									left:Number = NaN, top:Number = NaN, width:Number = 0, height:Number = 0):IFlexDisplayObject
		{
			if (parent == null)
			{
					parent = mx.core.FlexGlobals.topLevelApplication as DisplayObject;
					parent.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
			
			}
			var dialog:IFlexDisplayObject = PopUpManager.createPopUp(parent, dialogClass, false); // 这里第三个参数 true 表示: 弹出myPanel窗口后, 是否可以对父级操作, 值为true时, 就会产生背景模糊的效果, 并不能对父级的东西进行操作
			if (width > 0)
			{
				dialog.width = width;
			}
			if (height > 0)
			{
				dialog.height = height;
			}
			
			if (isNaN(left) && isNaN(top))
			{
				PopUpManager.centerPopUp(dialog);	
			}

			dialog.x = isNaN(left) ? 0 : left;
			dialog.y = isNaN(top) ? 0 : top;
			dialogTarget = dialog;
			return dialog;
		}
		
		public static function showModel(parent:DisplayObject, dialogClass:Class, 
										 left:Number = NaN, top:Number = NaN,width:Number = 0, height:Number = 0):IFlexDisplayObject
		{
			if (parent == null)
			{
				parent = mx.core.FlexGlobals.topLevelApplication as DisplayObject;
			}
			var dialog:IFlexDisplayObject = PopUpManager.createPopUp(parent, dialogClass, true); // 这里第三个参数 true 表示: 弹出myPanel窗口后, 是否可以对父级操作, 值为true时, 就会产生背景模糊的效果, 并不能对父级的东西进行操作
			if (width > 0)
			{
				dialog.width = width;
			}
			if (height > 0)
			{
				dialog.height = height;
			}
			
			if (isNaN(left) && isNaN(top))
			{
				PopUpManager.centerPopUp(dialog);	
			}
			
			dialog.x = isNaN(left) ? 0 : left;
			dialog.y = isNaN(top) ? 0 : top;
			
			return dialog;
		}
		
		public static function close(dialog:IFlexDisplayObject):void
		{
			PopUpManager.removePopUp(dialog);
			dialogTarget = null;
		}
		
		static private function getPopupControlBounds():Rectangle
		{
			var point:Point = dialogTarget.parent.localToGlobal(
				new Point(dialogTarget.x, dialogTarget.y));
			return new Rectangle(point.x, point.y, dialogTarget.width, dialogTarget.height);
		}
		
		/**
		 * 鼠标在应用程序任意位置点击。
		 * */
		static private function mouseDownHandler(event:MouseEvent) : void
		{
			if (dialogTarget)
			{
				var rect:Rectangle = getPopupControlBounds();
				var application:Object = FlexGlobals.topLevelApplication;
				if (!rect.containsPoint(new Point(application.mouseX, application.mouseY)))
				{
					PopUpManager.removePopUp(dialogTarget);
					dialogTarget = null;
				}
			}
		}
	}
}